package com.mimosa.common.system.menu;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

/**
 * 菜单信息的帮助类
 * 
 * @filename MenuItemHelper.java
 * @datetime 2013-9-27 下午12:07:55
 * @author ggeagle
 * 
 */
public final class MenuItemHelper {
	/**
	 * 日志记录器
	 */
	private static final Logger logger = LoggerFactory.getLogger(MenuItemHelper.class);
	/**
	 * 主键长度
	 */
	public static final int ID_LENGTH = 3;

	public static List<TMenuItem> getAllMenuItems() {
		return getAllMenuItems("/config/menu.xml");
	}

	@SuppressWarnings("unchecked")
	public static List<TMenuItem> getAllMenuItems(String fileName) {
		List<TMenuItem> menuItems = Collections.EMPTY_LIST;
		// 调用XML解析器
		SAXParserFactory parserFactory = SAXParserFactory.newInstance();
		SAXParser parser;
		try {
			parser = parserFactory.newSAXParser();
			MenuItemHandler handler = new MenuItemHandler();
			InputStream inputStream = MenuItemHandler.class.getResourceAsStream(fileName);
			if (inputStream == null) {
				logger.error("没有配置文件/config/menu.xml");
			} else {
				parser.parse(inputStream, handler);
			}
			// 设置要解析的文件及解析规则信息
			menuItems = handler.getMenuItemList();
		} catch (ParserConfigurationException e) {
			logger.error("解析菜单文件信息出错!");
		} catch (SAXException e) {
			logger.error("解析菜单时发生SAX异常！", e);
		} catch (IOException e) {
			logger.error("解析菜单信息时发生IO异常!", e);
		}
		return menuItems;
	}
}